/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.inmp.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.log4j.Logger;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-6-13 上午10:16:43          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class FilePersistUtil {

    private static final Logger logger = Logger.getLogger(FilePersistUtil.class);

    /**
     * 持久化临时数据，例如日志文件的采集，记录上次采集的状态。与getPersistentData相应使用
     * @param key
     * @param data
     * @throws IOException
     */
    public static void savePersistentData(String key, Serializable data) throws IOException {
        File saveDir = new File("save");
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }

        String fileName = "save/" + key + ".od";
        File file = new File(fileName);

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                logger.error("failed to create new file", e);
            }
        }
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(data);
            oos.flush();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    logger.error("failed to colse ObjectOutputStream", e);
                }
            }
        }
    }

    /**
     * 获取持久化临时数据，例如日志文件的采集，记录上次采集的状态。与savePersistentData相应使用
     * @param key
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Serializable getPersistentData(String key) throws IOException, ClassNotFoundException {
        String fileName = "save/" + key + ".od";
        File file = new File(fileName);
        if (!file.exists()) {
            return null;
        }
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(file));
            return (Serializable) ois.readObject();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    logger.error("failed to colse ObjectOutputStream", e);
                }
            }
        }
    }

}
